package visualizer.input.concrete;

import java.awt.event.KeyEvent;
import java.util.regex.Pattern;

import processing.core.PFont;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PVector;
import visualizer.App;
import visualizer.data.DataSource;

public class TextInputComponent extends GraphicalComponent<String> {
	private Pattern acceptedChars = Pattern.compile("[a-zA-Z0-9 -+]");
	private int fontSize = 30;
	private PFont myFont;


	public TextInputComponent(PVector position, PImage[] background,
			DataSource<String> input, App a) {
		super(position, background, input);
		myFont = a.createFont("Arial", fontSize);
	}

	protected void drawRelative(PGraphics g) {
		super.drawRelative(g);
		g.textFont(myFont);
		g.pushMatrix();
		g.translate(25, 50);
		g.text(getInput().get());
		g.popMatrix();
	}

	public void handleKeyPress(char key) {
		switch (key) {
		case KeyEvent.VK_BACK_SPACE:
			if(!getInput().get().isEmpty()){
				String input = getInput().get();
				input = input.substring(0, input.length() - 1);
				getInput().set(input);
			}
			break;
		default:
			if (acceptedChars.matcher("" + key).matches() && getInput().get().length() < 20) {
				getInput().set(getInput().get() + key);
			}
		}
	}
}
